import { asyncTasks } from 'roc-utils'
import db from '../app/database.js'
import api from '../utils/apiBase.js'
import { md5 } from '../utils/crypto-utils.js'
import redisClient from '../app/redis.js'

class RegisterService {
    /**
     * 用户注册
     * @param {string} nickname
     * @param {string} username
     * @param {string} password
     * @param {string} uuid
     * @param {string} captcha
     * @returns {Promise<{code: number, data: *, message: string}|{code: number, data: string, message: string}|void>}
     */
    async register(nickname, username, password, uuid, captcha) {
        if (!uuid) {
            return api.error('uuid为空!')
        }
        const redisCaptcha = await redisClient.get(uuid)
        if (!nickname) {
            return api.error('昵称为空!')
        } else if (!username) {
            return api.error('用户名为空!')
        } else if (!password) {
            return api.error('密码为空!')
        } else if (!captcha) {
            return api.error('验证码为空!')
        } else if (captcha !== redisCaptcha) {
            return api.error('验证码错误!')
        }
        const selectSql = 'SELECT * FROM roc_user WHERE username = ?'
        const [err1, results1] = await asyncTasks(db.query(selectSql, [username]))
        if (err1) return console.log('sql错误:', err1.sqlMessage)
        const users = results1[0]
        if (users.length) return api.error('用户名已存在')
        const sqlInsert =
            'INSERT INTO roc_user(nickname, username, password, add_time) VALUES(?, ?, ?, ?)'
        const [err, results] = await asyncTasks(
            db.query(sqlInsert, [nickname, username, md5(password), new Date()]),
        )
        if (err) return console.log('sql错误:', err.sqlMessage)
        await redisClient.del(uuid)
        return api.success(results[0].insertId)
    }
}

export default new RegisterService()
